import java.util.Date;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class CountDownLatchDemo {
    private static final int NUMBER = 5;
    private static final CountDownLatch cdLatch = new CountDownLatch(NUMBER);
    //random不是线程安全的
    private static AtomicInteger nextId = new AtomicInteger(1);
    private static Random random = new Random(20210117);

    static class Downloader extends Thread {
        Downloader() {
            super(String.format("下载线程(%d)", nextId.getAndIncrement()));
        }

        @Override
        public void run() {
            try {
                TimeUnit.SECONDS.sleep(random.nextInt(8) + 2);
                System.out.println(new Date() + ":" + getName() + "下载成功");
                cdLatch.countDown();//cdLatch被调用了NUMBERS次的时候，await()才会继续执行
            } catch (InterruptedException e) {
            }
        }

        public static void main(String[] args) {
            System.out.println("一共创建" + NUMBER + "个线程进行下载");
            for (int i = 0; i < NUMBER; i++) {
                new Downloader().start();
            }
            //等着所有的人全部下载成功
            try {
                cdLatch.await();
            } catch (InterruptedException e) {
            }
            System.out.println("下载成功");
        }
    }
}
